package work;


import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
@WebServlet("/servlet1")
public class servlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取提交来的参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String score = req.getParameter("score");
//        保存到文件中
//        获取域对象
        ServletContext context = getServletContext();
//        获取真实路径
        String realPath = context.getRealPath("stu.txt");
//        获取输出流
        FileWriter fw = new FileWriter(realPath, true);
//        输出数据
        fw.write(name+","+age+","+score);
//        输出换行
        fw.write(System.lineSeparator());
        fw.close();
//        处理乱码
        resp.setContentType("text/html;charset=utf-8");
//        给出提示
        resp.getWriter().write("添加成功");
//        返回主界面
        resp.setHeader("Refresh","2,URL=/homeworkday08/stu.html");
    }
}
